package com.xcity.game.financial;

import com.alibaba.fastjson.annotation.JSONField;
import com.xcity.db.entity.Player;
import com.xcity.game.common.Cause;

import naga.x.game.time.TimeUpdater;

public class PlayerFinancial {

	@JSONField(name = "1")
	private int id; // 理财产品id
	@JSONField(name = "2")
	private long amount; // 购买金额
	@JSONField(name = "3")
	private long buyTime; // 购买时间
	@JSONField(name = "4")
	private long interest; // 利息
	@JSONField(name = "5")
	private long interestGot; // 已领取的利息
	@JSONField(name = "6")
	private int period; // 周期(天)
	
	public PlayerFinancial() {}
	
	public PlayerFinancial(int id, long amount, long interest, int period) {
		this.id = id;
		this.amount = amount;
		this.interest = interest;
		this.buyTime = TimeUpdater.getInstance().now();
		this.period = period;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public long getAmount() {
		return amount;
	}

	public void setAmount(long amount) {
		this.amount = amount;
	}

	public long getBuyTime() {
		return buyTime;
	}

	public void setBuyTime(long buyTime) {
		this.buyTime = buyTime;
	}

	public long getInterest() {
		return interest;
	}

	public void setInterest(long interest) {
		this.interest = interest;
	}

	public long getInterestGot() {
		return interestGot;
	}

	public void setInterestGot(long interestGot) {
		this.interestGot = interestGot;
	}

	public int getPeriod() {
		return period;
	}

	public void setPeriod(int period) {
		this.period = period;
	}
	
	/**
	 * 检测当前是否可领取利息
	 * @return
	 */
	public boolean canReceiveInterest() {
		if (interestGot >= interest) { // 已领完
			return false;
		}
		int elapseDay = (int) ((TimeUpdater.getInstance().now() - buyTime) / (1000 * 60 * 60 * 24));
		if (elapseDay <= 0) {
			return false;
		}
		long val;
		if (elapseDay >= period) { // 已到期，应全部领取
			val = interest - interestGot;
		} else {
			val = interest * elapseDay / period - interestGot;
		}
		return val > 0;
	}
	
	public boolean receiveInterest(Player owner) {
		if (interestGot >= interest) { // 已领完
			return false;
		}
		int elapseDay = (int) ((TimeUpdater.getInstance().now() - buyTime) / (1000 * 60 * 60 * 24));
		if (elapseDay <= 0) {
			return false;
		}
		long val;
		if (elapseDay >= period) { // 已到期，应全部领取
			val = interest - interestGot;
			owner.addGold(amount, Cause.FINANCIAL_RETURN); // 还本金
		} else {
//			long interestPerDay = f.getInterest() / f.getPeriod();
			val = interest * elapseDay / period - interestGot;
		}
		if (val <= 0) {
			return false;
		}
		interestGot += val;
		owner.addGold(val, Cause.FINANCIAL_INTEREST);
		return true;
	}

}
